# coding: utf-8
from datetime import datetime

from sqlalchemy import Column, Integer, String, DATETIME
from sqlalchemy.orm import Session

from ...db import DbBase


class TableSearchHistory(DbBase):
    __tablename__ = 'search_history'
    id = Column(Integer, autoincrement=True, primary_key=True)
    key = Column(String(255), nullable=False)
    created_time = Column(DATETIME, nullable=False)


def search_history_exist(key: str, session: Session) -> bool:
    return session.query(TableSearchHistory).filter_by(key=key).first() is not None


def add_search_history(key: str, session: Session) -> None:
    if search_history_exist(key, session):
        return
    session.add(TableSearchHistory(key=key, created_time=datetime.now()))
    session.commit()


def get_search_history(session: Session) -> list:
    return session.query(TableSearchHistory).order_by(TableSearchHistory.created_time.desc()).all()


def clear_search_history(session: Session) -> None:
    session.query(TableSearchHistory).delete()
    session.commit()
